﻿using EnterpriseInformation.Common;
using HtmlAgilityPack;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace EnterpriseInformation.DataModel
{
    public class BasicalInformation : CustomLog
    {


        RegexClass regexClass;
        string HtmlComtent;
        public HtmlDocument doc;
        public HtmlNodeCollection basicRows;
        public HtmlNodeCollection ComInfos;

        public BasicalInformation(string companyName,string unique, UserHelper userHelper)
        {

            string userName = userHelper.UserName;
            InitLog(userName);
            this.UserName = userName;
            this.CompanyName = companyName;
            this.Unique = unique;
            regexClass = new RegexClass();
        }


        /// <summary>
        /// 初始化
        /// </summary>
        /// <param name="htmlContent"></param>
        public void Init(string htmlContent) 
        {

            try
            {
                 
                doc = new HtmlDocument();
                doc.LoadHtml(htmlContent);

                this.HtmlComtent = htmlContent;

                //基础信息
                basicRows = doc.DocumentNode.SelectNodes("//div[@class=\"dcontent\"]/div[@class=\"row\"]");

                // 营业执照信息
                ComInfos = doc.DocumentNode.SelectNodes("//section[@id=\"Cominfo\"]//tr");


            }
            catch (Exception ex)
            {
                MyLog().Error("基本信息初始化:" + ex.ToString());
            } 

        }




        /// <summary>
        /// 获取单元格内的值
        /// </summary>
        /// <param name="rootNode"></param>
        /// <returns></returns>
        public string GetCellInfo(HtmlNode rootNode)
        {
            string nodeValue = string.Empty;

            try
            {


                HtmlNodeCollection elementNodes = rootNode.SelectNodes("./*");

                bool childTable = false;

                if (elementNodes != null && elementNodes.Count > 0)
                {
                    HtmlNodeCollection tableNodes = rootNode.SelectNodes("./table");

                    if (tableNodes != null && tableNodes.Count > 0)
                    {
                        childTable = true;

                        JObject jobj_cell = null;

                        if (childTable)
                        {
                            HtmlNodeCollection trNodes = rootNode.SelectNodes(".//tr");

                            foreach (HtmlNode trItem in trNodes)
                            {

                                HtmlNodeCollection tdNodes = trItem.SelectNodes("./td");

                                if (tdNodes != null && tdNodes.Count > 0 && jobj_cell == null)
                                {
                                    jobj_cell = new JObject();
                                }

                                foreach (HtmlNode tdItem in tdNodes)
                                {
                                    HtmlNodeCollection hrefNodes = tdItem.SelectNodes("./a");

                                    HtmlNodeCollection linkNodes = tdItem.SelectNodes("./a/span/text()");

                                    if (linkNodes == null || linkNodes.Count < 1)
                                    {
                                        continue;
                                    }

                                    jobj_cell.Add(new JProperty("name", linkNodes[0].InnerText));

                                    jobj_cell.Add(new JProperty("url", hrefNodes[0].GetAttributeValue("href", null)));


                                }


                            }

                        }


                        if (jobj_cell != null)
                        {
                            nodeValue = jobj_cell.ToString();
                        }
                        else
                        {
                            nodeValue = "error value!";

                        }
                    }

                }

                //没有嵌套table节点
                if (!childTable)
                {
                    nodeValue = rootNode.InnerText.Replace(" ", "").Trim();
                }

            }
            catch (Exception ex)
            {
                MyLog().Error("标签:" + ex.ToString());

                nodeValue = "data error!";
            }

            return nodeValue;


        }


        /// <summary>
        /// 分页请求
        /// </summary>
        /// <param name="moduleName"></param>
        /// <returns></returns>
        public JObject CreatePagination(string moduleName) 
        { 
            JObject param = new JObject();
            JObject query = new JObject();                  
            query.Add(new JProperty("unique", Unique));
            query.Add(new JProperty("companyname", CommonClass.UrlEncode(CompanyName)));
            query.Add(new JProperty("tab", "base"));
            query.Add(new JProperty("box", moduleName));
            query.Add(new JProperty("touzistatus", ""));
            query.Add(new JProperty("touziratio", ""));
            query.Add(new JProperty("touzicapi", ""));
            query.Add(new JProperty("p", ""));
            param.Add(new JProperty("param", query));
            param.Add(new JProperty("url", "/company_getinfos")); 
            return param; 
        }


        public string CompanyName {
            get;
            set;
        }

        public string Unique { get; set; }


        /// <summary>
        /// 标签
        /// </summary>
        public JArray TagList
        {
            set {; }
            get {
                try
                {
                    JArray list = new JArray();

                    HtmlNodeCollection tagNodes =
                         doc.DocumentNode.SelectNodes("//div[@class=\"content\"]/div[contains(@class,\"row\") and contains(@class,\"tags\")]");


                    HtmlNodeCollection childTagNodes = tagNodes[0].SelectNodes("./*/text()|./*/*/text()");

                    foreach (HtmlNode childNoteItem in childTagNodes)
                    {

                        string tagText = childNoteItem.InnerText.Replace(" ","").Replace("\n", "");

                        if (!string.IsNullOrEmpty(tagText))
                        {
                            list.Add(tagText);
                        }
                         
                    }

                    return list;

                }
                catch (Exception ex)
                {
                    MyLog().Error("标签:" + ex.ToString());
                }

                return new JArray();

            }
        }


        /// <summary>
        /// 电话
        /// </summary>
        public string PhoneNum {

            set {; }

            get {

                try
                {

                    HtmlNodeCollection phoneNodes = basicRows[0].SelectNodes("./span[contains(@class,\"fc\")]/span[contains(@class,\"cvlu\")]");

                    HtmlNodeCollection phoneNodeSpan = phoneNodes[0].SelectNodes("./span");

                    string phoneNum = string.Empty;

                    if (phoneNodeSpan != null && phoneNodeSpan.Count > 0)
                    {
                        phoneNum = phoneNodeSpan[0].InnerText;

                    }
                    else {

                        phoneNum = phoneNodes[0].InnerText;
                    }
                     

                    phoneNum = phoneNum.Replace(" ", "").Trim();

                    return phoneNum;

                }

                catch (Exception ex)
                {
                    MyLog().Error("电话:" + ex.ToString());
                }

                return "****-********";


            }

        }


        /// <summary>
        /// 官网
        /// </summary>
        public string WebSite
        {
            set {; }
            get {

                try
                {

                    string webSite = basicRows[0].SelectNodes("./span[contains(@class,\"cvlu\")]/a")[0].InnerText;

                    webSite = webSite.Replace(" ", "").Trim();

                    return webSite;

                }
                catch (Exception ex)
                {

                    MyLog().Error("官网:" + ex.ToString());
                }

                return "http://*";


            }
        }


        /// <summary>
        /// 邮箱
        /// </summary>
        public string MailBox
        {
            set
            {
                ;
            }
            get {

                try
                {
                    HtmlNodeCollection mailBoxNodes = basicRows[1].SelectNodes("./span[contains(@class,\"fc\")]/span");

                    HtmlNodeCollection mailBoxNode = mailBoxNodes[0].SelectNodes("./a");

                    string mailBox = string.Empty;

                    if (mailBoxNode != null && mailBoxNode.Count > 0)
                    {
                        mailBox = mailBoxNode[0].InnerText;

                    }
                    else {

                        mailBox = mailBoxNodes[0].InnerText;
                    }

                    
                    mailBox = mailBox.Replace(" ", "").Trim();

                    return mailBox;

                }
                catch (Exception ex)
                {

                    MyLog().Error("邮箱:" + ex.ToString());
                }

                return "http://*@*.com";
            }
        }


        /// <summary>
        /// 地址
        /// </summary>
        public string Address
        {

            set
            {
                ;
            }
            get
            {

                try
                {

                    string address = basicRows[1].SelectNodes("./span[contains(@class,\"cvlu\")]/a/text()")[0].InnerText;

                    address = address.Replace(" ", "").Trim();

                    return address;

                }
                catch (Exception ex)
                {

                    MyLog().Error("地址:" + ex.ToString());
                }

                return "******";
            }

        }


        /// <summary>
        /// 公司简介
        /// </summary>
        public string Intruduce
        {
            set {; }
            get {

                try
                {
                    string intruduce = string.Empty;

                    if (basicRows.Count > 2)
                    {
                         intruduce = basicRows[2].SelectNodes("./span[contains(@class,\"introExpand\")]/text()")[0].InnerText; 

                    }

                    intruduce = intruduce.Replace(" ", "").Trim();

                    return intruduce;



                }
                catch (Exception ex)
                {

                    MyLog().Error("公司简介:" + ex.ToString());
                }

                return "******";


            }

        }



        /// <summary>
        /// 法人代表
        /// </summary>
        public string LegalRep
        {
            set {; }
            get {

                try
                {

                    string legalRep = ComInfos[0].SelectNodes("./td/div[contains(@class,\"boss-td\")]//h2")[0].InnerText;

                    legalRep = legalRep.Replace(" ", "").Trim();

                    return legalRep;

                }
                catch (Exception ex)
                {

                    MyLog().Error("法人代表:" + ex.ToString());
                }

                return "******";


            }

        }


        /// <summary>
        /// 登记状态
        /// </summary>
        public string RegistrationStatus
        {
            set {; }
            get
            {

                try
                {

                    string registrationStatus = ComInfos[0].SelectNodes("./td")[3].InnerText;

                    registrationStatus = registrationStatus.Replace(" ", "").Trim();

                    return registrationStatus;

                }
                catch (Exception ex)
                {

                    MyLog().Error("登录状态:" + ex.ToString());
                }

                return "******";


            }

        }




        /// <summary>
        /// 成立日期
        /// </summary>
        public string BuildDate
        {
            set {; }
            get
            {

                try
                {

                    string buildDate = ComInfos[0].SelectNodes("./td")[5].InnerText;

                    buildDate = buildDate.Replace(" ", "").Trim();

                    return buildDate;

                }
                catch (Exception ex)
                {

                    MyLog().Error("成立日期:" + ex.ToString());
                }

                return "******";


            }

        }


        /// <summary>
        /// 注册资本
        /// </summary>
        public string Capital
        {
            set {; }
            get
            {

                try
                {

                    string capital = ComInfos[1].SelectNodes("./td")[1].InnerText;

                    capital = capital.Replace(" ", "").Trim();

                    return capital;

                }
                catch (Exception ex)
                {

                    MyLog().Error("注册资本:" + ex.ToString());
                }

                return "******";


            }

        }




        /// <summary>
        /// 实缴资本
        /// </summary>
        public string IssuedCapital
        {
            set {; }
            get
            {

                try
                {

                    string issuedCapital = ComInfos[1].SelectNodes("./td")[3].InnerText;

                    issuedCapital = issuedCapital.Replace(" ", "").Trim();

                    return issuedCapital;

                }
                catch (Exception ex)
                {

                    MyLog().Error("成立日期:" + ex.ToString());
                }

                return "******";


            }

        }




        /// <summary>
        /// 核准日期
        /// </summary>
        public string CheckDate
        {
            set {; }
            get
            {

                try
                {

                    string checkDate = ComInfos[1].SelectNodes("./td")[5].InnerText;

                    checkDate = checkDate.Replace(" ", "").Trim();

                    return checkDate;

                }
                catch (Exception ex)
                {

                    MyLog().Error("核准日期:" + ex.ToString());
                }

                return "******";


            }

        }




        /// <summary>
        /// 统一社会信用代码
        /// </summary>
        public string SocialCode
        {
            set {; }
            get
            {

                try
                {

                    string socialCode = ComInfos[2].SelectNodes("./td")[1].InnerText;

                    socialCode = socialCode.Replace(" ", "").Trim();

                    return socialCode;

                }
                catch (Exception ex)
                {

                    MyLog().Error("统一社会信用代码:" + ex.ToString());
                }

                return "******";


            }

        }



        /// <summary>
        /// 组织机构代码
        /// </summary>
        public string OrganizationCode
        {
            set {; }
            get
            {

                try
                {
                    string oganizationCode = ComInfos[2].SelectNodes("./td")[3].InnerText;

                    oganizationCode = oganizationCode.Replace(" ", "").Trim();

                    return oganizationCode;

                }
                catch (Exception ex)
                {

                    MyLog().Error("组织机构代码:" + ex.ToString());
                }

                return "******";


            }

        }



        /// <summary>
        /// 工商注册号
        /// </summary>
        public string RegistrationCode
        {
            set {; }
            get
            {

                try
                {
                    string registrationCode = ComInfos[2].SelectNodes("./td")[5].InnerText;

                    registrationCode = registrationCode.Replace(" ", "").Trim();

                    return registrationCode;

                }
                catch (Exception ex)
                {

                    MyLog().Error("工商注册号:" + ex.ToString());
                }

                return "******";


            }

        }


        /// <summary>
        /// 纳税人识别号
        /// </summary>
        public string TaxpayerCode
        {
            set {; }
            get
            {

                try
                {
                    string taxpayerCode = ComInfos[3].SelectNodes("./td")[1].InnerText;

                    taxpayerCode = taxpayerCode.Replace(" ", "").Trim();

                    return taxpayerCode;

                }
                catch (Exception ex)
                {

                    MyLog().Error("纳税人识别号:" + ex.ToString());
                }

                return "******";


            }

        }


        /// <summary>
        /// 进出口企业代码
        /// </summary>
        public string ExportCode
        {
            set {; }
            get
            {

                try
                {
                    string exportCode = ComInfos[3].SelectNodes("./td")[3].InnerText;

                    exportCode = exportCode.Replace(" ", "").Trim();

                    return exportCode;

                }
                catch (Exception ex)
                {

                    MyLog().Error("进出口企业代码:" + ex.ToString());
                }

                return "******";


            }

        }



        /// <summary>
        /// 所属行业
        /// </summary>
        public string IndustryCode
        {
            set {; }
            get
            {

                try
                {
                    string industryCode = ComInfos[3].SelectNodes("./td")[5].InnerText;

                    industryCode = industryCode.Replace(" ", "").Trim();

                    return industryCode;

                }
                catch (Exception ex)
                {

                    MyLog().Error("所属行业:" + ex.ToString());
                }

                return "******";


            }

        }


        /// <summary>
        /// 企业类型
        /// </summary>
        public string EnterpriseType
        {
            set {; }
            get
            {

                try
                {
                    string enterpriseType = ComInfos[4].SelectNodes("./td")[1].InnerText;

                    enterpriseType = enterpriseType.Replace(" ", "").Trim();

                    return enterpriseType;

                }
                catch (Exception ex)
                {

                    MyLog().Error("企业类型:" + ex.ToString());
                }

                return "******";


            }

        }



        /// <summary>
        /// 营业期限
        /// </summary>
        public string OperationEnding
        {
            set {; }
            get
            {

                try
                {
                    string operationEnding = ComInfos[4].SelectNodes("./td")[3].InnerText;

                    operationEnding = operationEnding.Replace(" ", "").Trim();

                    return operationEnding;

                }
                catch (Exception ex)
                {

                    MyLog().Error("营业期限:" + ex.ToString());
                }

                return "******";


            }

        }



        /// <summary>
        /// 登记机关
        /// </summary>
        public string Authority
        {
            set {; }
            get
            {

                try
                {
                    string authority = ComInfos[4].SelectNodes("./td")[5].InnerText;

                    authority = authority.Replace(" ", "").Trim();

                    return authority;

                }
                catch (Exception ex)
                {

                    MyLog().Error("登记机关:" + ex.ToString());
                }

                return "******";


            }

        }



        /// <summary>
        /// 人员规模
        /// </summary>
        public string StaffSize
        {
            set {; }
            get
            {

                try
                {
                    string staffSize = ComInfos[5].SelectNodes("./td")[1].InnerText;

                    staffSize = staffSize.Replace(" ", "").Trim();

                    return staffSize;

                }
                catch (Exception ex)
                {

                    MyLog().Error("人员规模:" + ex.ToString());
                }

                return "******";


            }

        }



        /// <summary>
        /// 参保人数
        /// </summary>
        public string InsuredSize
        {
            set {; }
            get
            {

                try
                {
                    string insuredSize = ComInfos[5].SelectNodes("./td")[3].InnerText;

                    insuredSize = insuredSize.Replace(" ", "").Trim();

                    return insuredSize;

                }
                catch (Exception ex)
                {

                    MyLog().Error("参保人数:" + ex.ToString());
                }

                return "******";


            }

        }


        /// <summary>
        /// 所属地区
        /// </summary>
        public string Area
        {
            set {; }
            get
            {

                try
                {
                    string area = ComInfos[5].SelectNodes("./td")[5].InnerText;

                    area = area.Replace(" ", "").Trim();

                    return area;

                }
                catch (Exception ex)
                {

                    MyLog().Error("所属地区:" + ex.ToString());
                }

                return "******";


            }

        }



        /// <summary>
        /// 曾用名
        /// </summary>
        public string OnceName
        {
            set {; }
            get
            {

                try
                {
                    string onceName = ComInfos[6].SelectNodes("./td")[1].InnerText;

                    onceName = onceName.Replace(" ", "").Trim();

                    return onceName;

                }
                catch (Exception ex)
                {

                    MyLog().Error("曾用名:" + ex.ToString());
                }

                return "******";


            }

        }



        /// <summary>
        /// 英文名
        /// </summary>
        public string EnglishName
        {
            set {; }
            get
            {

                try
                {
                    string englishName = ComInfos[6].SelectNodes("./td")[3].InnerText;

                    englishName = englishName.Replace(" ", "").Trim();

                    return englishName;

                }
                catch (Exception ex)
                {

                    MyLog().Error("英文名:" + ex.ToString());
                }

                return "******";


            }

        }



        /// <summary>
        /// 企业地址
        /// </summary>
        public string CompanyAddress
        {
            set {; }
            get
            {

                try
                {
                    string companyAddress = ComInfos[7].SelectNodes("./td")[1].InnerText;

                    companyAddress = companyAddress.Replace(" ", "").Trim();

                    return companyAddress;

                }
                catch (Exception ex)
                {

                    MyLog().Error("企业地址:" + ex.ToString());
                }

                return "******";
            }

        }



        /// <summary>
        /// 经营范围
        /// </summary>
        public string CompanyScope
        {
            set {; }
            get
            {
                try
                {
                    string companyScope = ComInfos[8].SelectNodes("./td")[1].InnerText;

                    companyScope = companyScope.Replace(" ", "").Trim();

                    return companyScope;

                }
                catch (Exception ex)
                {

                    MyLog().Error("经营范围:" + ex.ToString());
                }

                return "******";
            }

        }


        /// <summary>
        /// 股东信息
        /// </summary>
        public JObject PartnernsInfo
        {
            set {; }
            get
            {
                try
                {
                    JObject partnernsInfo = new JObject();

                    HtmlNodeCollection partnerns =
                        doc.DocumentNode.SelectNodes("//*[@id=\"partnerslist\"]/table/tr");

                    bool isIpo = false;

                    string partnernsCount = string.Empty;

                    try
                    {

                        HtmlNodeCollection partnerNodes = doc.DocumentNode.SelectNodes("//*[@id=\"partnerslist\"]/div[@class=\"tcaption\"]/span[@class=\"tbadge\"]/text()");

                        if (partnerNodes != null)
                        {
                            partnernsCount = partnerNodes[0].InnerText;

                        }
                        else
                        {  //中国平安 最新公示 10

                            partnerNodes = doc.DocumentNode.SelectNodes("//*[@id=\"partnern\"]/div[contains(@class,\"tnavtap\")]/a[contains(@class,\"active\")]/text()");

                            if (partnerNodes != null)
                            {
                                partnernsCount = partnerNodes[0].InnerText;

                                partnernsCount = regexClass.RegexString(partnernsCount, "(?<g1>[\\d]+)", "g1");
 
                                isIpo = true;


                                //上市公司的信息
                                partnerns = doc.DocumentNode.SelectNodes("//*[@id=\"ipopartnerslist\"]/table/tr");


                            }

                        }



                    }
                    catch (Exception ex)
                    {
                        MyLog().Error("股东信息:" + ex.ToString());

                    }
                     

                    partnernsInfo.Add(new JProperty("count", partnernsCount));

                    JArray partnerns_array = new JArray();

                    for (int i = 1; i < partnerns.Count; i++)
                    {
                        HtmlNodeCollection partnernTds = partnerns[i].SelectNodes("./td");

                        JObject partnernItem = new JObject();

                        //股东及出资信息
                        string partnernInfo = GetCellInfo(partnernTds[1]);

                        if (partnernInfo.StartsWith("{"))
                        {
                            partnernItem.Add(new JProperty("partnern_info", JObject.Parse(partnernInfo)));

                        } else {

                            partnernItem.Add(new JProperty("partnern_info", partnernInfo));

                        }

                       

                        //持股比例
                        string shareInfos = GetCellInfo(partnernTds[2]);

                        partnernItem.Add(new JProperty("share_infos", shareInfos));


                        if (!isIpo)
                        {

                            //认缴出资额(万元) 
                            string givenMoney = GetCellInfo(partnernTds[3]);

                            partnernItem.Add(new JProperty("given_money", givenMoney));

                            //认缴出资日期
                            string givenDate = GetCellInfo(partnernTds[4]);

                            partnernItem.Add(new JProperty("given_date", givenDate));

                        }
                        else {

                            //持股数(股)
                            string share_size = GetCellInfo(partnernTds[3]);

                            partnernItem.Add(new JProperty("share_size", share_size));

                        }
 
                          

                        partnerns_array.Add(partnernItem);

                    }

                    partnernsInfo.Add(new JProperty("is_ipo", isIpo));
                    partnernsInfo.Add(new JProperty("partnerns", partnerns_array));
                    partnernsInfo.Add(new JProperty("comment", "股东信息"));

                    return partnernsInfo;

                }
                catch (Exception ex)
                {

                    MyLog().Error("股东信息:" + ex.ToString());
                }

                return new JObject();
            }

        }


        /// <summary>
        /// 主要人员
        /// </summary>
        public JObject EmployeesList 
        {
            set {; }
            get {
                 

                try
                {

                    JObject employeesList = new JObject();

                    HtmlNodeCollection employees_list =
                      doc.DocumentNode.SelectNodes("//*[@id=\"employeeslist\"]/table/tr");

                    string member_count = string.Empty;

                    bool isIpo = false;

                    try
                    {

                        HtmlNodeCollection memberNodes = doc.DocumentNode.SelectNodes("//*[@id=\"Mainmember\"]/div[@class=\"tcaption\"]/span[@class=\"tbadge\"]/text()");

                        if (memberNodes != null)
                        {
                            member_count = memberNodes[0].InnerText;

                        }  else
                        {  //最新公示 23

                            memberNodes = doc.DocumentNode.SelectNodes("//*[@id=\"Mainmember\"]/div[@class=\"tnavtap\"]/a[contains(@class,\"active\")]/text()");

                            if (memberNodes != null) 
                            {
                                member_count = memberNodes[0].InnerText;

                                member_count = regexClass.RegexString(member_count, "(?<g1>[\\d]+)", "g1");

                                isIpo = true;

                                employees_list =   doc.DocumentNode.SelectNodes("//*[@id=\"ipoemployeeslist\"]/table/tr");
                            }

                        }

                      

                    }
                    catch (Exception ex)
                    {
                        MyLog().Error("主要人员:" + ex.ToString());

                    }

                  

                    employeesList.Add(new JProperty("count", member_count)); 

                    JArray member_array = new JArray(); 

                    for (int i = 1; i < employees_list.Count; i++)
                    {
                        HtmlNodeCollection employeesTds = employees_list[i].SelectNodes("./td");


                        JObject member = new JObject();

                        //姓名
                        string employees_name= GetCellInfo(employeesTds[1]);


                        if (employees_name.StartsWith("{"))
                        {
                            member.Add(new JProperty("employees_name", JObject.Parse(employees_name)));

                        }
                        else
                        {
                            member.Add(new JProperty("employees_name", employees_name));
                        }

                        string employees_position = string.Empty;
                        string share_infos = string.Empty;


                        if (!isIpo)
                        { 

                            //职务
                            employees_position = GetCellInfo(employeesTds[2]);
                            member.Add(new JProperty("employees_position", employees_position));


                            //持股比例
                            share_infos = GetCellInfo(employeesTds[3]);

                            member.Add(new JProperty("share_infos", share_infos));

                            //持股比例
                            string share_final_infos = GetCellInfo(employeesTds[4]);
                           
                            member.Add(new JProperty("share_final_infos", share_final_infos));


                        }
                        else {

                            //性别
                            string gender = GetCellInfo(employeesTds[2]);

                            member.Add(new JProperty("gender", gender));

                            //学历
                            string education = GetCellInfo(employeesTds[3]);

                            member.Add(new JProperty("education", education));

                            //职务
                            employees_position = GetCellInfo(employeesTds[4]);

                            member.Add(new JProperty("employees_position", employees_position));

                            //薪水
                            string salary = GetCellInfo(employeesTds[5]);

                            member.Add(new JProperty("salary", salary));

                            //持股数
                            string shares = GetCellInfo(employeesTds[6]);
                            member.Add(new JProperty("shares", shares));

                            //持股比例
                            share_infos = GetCellInfo(employeesTds[7]);

                            member.Add(new JProperty("share_infos", share_infos));

                            //最终受益股份
                            string share_planing = GetCellInfo(employeesTds[8]);

                            member.Add(new JProperty("share_planing", share_planing));

                            //本届任期
                            string period = GetCellInfo(employeesTds[9]);

                            member.Add(new JProperty("period", period));


                            //公告日期
                            string publish_date = GetCellInfo(employeesTds[10]);

                            member.Add(new JProperty("publish_date", publish_date));

                        }



                        member.Add(new JProperty("is_ipo", isIpo));
                        
                         
                        member_array.Add(member);

                    }

                    employeesList.Add(new JProperty("members", member_array));
                    employeesList.Add(new JProperty("comment", "主要人员"));

                    return employeesList;

                }
                catch (Exception ex)
                { 
                    MyLog().Error("主要人员:" + ex.ToString());
                }


                return new JObject();

            }
        
        }


        /// <summary>
        /// 对外投资解析
        /// </summary>
        /// <param name="nodesCollection"></param>
        /// <returns></returns>
        public JArray ParseInvest(HtmlNodeCollection nodesCollection) 
        {
            try
            {

                JArray invest_array = new JArray();

                for (int i = 1; i < nodesCollection.Count; i++)
                {
                    HtmlNodeCollection tzTds = nodesCollection[i].SelectNodes("./td");

                    //被投资企业名称
                    string legal_enterprise = GetCellInfo(tzTds[1]);

                    //法定代表人
                    string legal_resp = GetCellInfo(tzTds[2]);

                    //注册资本
                    string capital = GetCellInfo(tzTds[3]);

                    //投资比例
                    string capital_size = GetCellInfo(tzTds[4]);

                    //投资数额
                    string capital_value = GetCellInfo(tzTds[5]);

                    //成立日期
                    string build_date = GetCellInfo(tzTds[6]);

                    //状态
                    string registration_status = GetCellInfo(tzTds[7]);
                     
                    JObject invest = new JObject();

                    if (legal_enterprise.StartsWith("{"))
                    {
                        invest.Add(new JProperty("legal_enterprise", JObject.Parse(legal_enterprise)));
                    }
                    else 
                    {

                        invest.Add(new JProperty("legal_enterprise", legal_enterprise));

                    }

                    if (legal_resp.StartsWith("{"))
                    {
                        invest.Add(new JProperty("legal_resp", JObject.Parse(legal_resp)));
                    }
                    else
                    {

                        invest.Add(new JProperty("legal_resp", legal_resp));

                    }
                     
                    invest.Add(new JProperty("capital", capital));
                    invest.Add(new JProperty("capital_size", capital_size));
                    invest.Add(new JProperty("capital_value", capital_value));
                    invest.Add(new JProperty("build_date", build_date));
                    invest.Add(new JProperty("registration_status", registration_status));

                    if (tzTds.Count > 8)
                    {
                        //融资轮次
                        string financing_round = GetCellInfo(tzTds[8]);
                        invest.Add(new JProperty("financing_round", financing_round));

                        //融资日期
                        string financing_date = GetCellInfo(tzTds[9]);

                        invest.Add(new JProperty("financing_date", financing_date));

                    }

                    if (tzTds.Count > 10)
                    {
                        //关联产品/机构
                        string connect_enterprise = GetCellInfo(tzTds[10]);
                        invest.Add(new JProperty("connect_enterprise", connect_enterprise));
                    }


                    invest_array.Add(invest);

                }

                return invest_array;

            }
            catch (Exception ex)
            {

                MyLog().Error("对外投资解析:" + ex.ToString());
            }


            return new JArray();


        }



        /// <summary>
        ///  对外投资翻页
        /// </summary>
        /// <param name="htmlContent"></param>
        /// <returns></returns>
        public JArray CallParseInvest(string htmlContent)
        {
            try
            {

                HtmlDocument tzDoc = new HtmlDocument();
                tzDoc.LoadHtml(htmlContent);

                HtmlNodeCollection invest_list =
                  tzDoc.DocumentNode.SelectNodes("//table[contains(@class,\"ntable\")]/*/tr");


                if (invest_list == null)
                {
                    throw new Exception("可能速度太快了!");
                }


                JArray invest_array = ParseInvest(invest_list);

                return invest_array;


            }
            catch (Exception ex)
            {

                MyLog().Error("对外投资翻页:" + ex.ToString());
            }

            return new JArray();
        }

        /// <summary>
        /// 对外投资
        /// </summary>
        public JObject InvestList 
        {
            set {; }
            get
            {

                try
                {

                    JObject investList = new JObject();

                    //try
                    //{

                    //    string t1 = regexClass.RegexString(HtmlComtent, "<(?<HtmlTag>[\\w]+)[^>]*\\s[iI][dD]=(?<Quote>[\"']?)touzilist(?(Quote)\\k<Quote>)[\"']?[^>]*?(/>|>((?<Nested><\\k<HtmlTag>[^>]*>)|</\\k<HtmlTag>>(?<-Nested>)|.*?)*</\\k<HtmlTag>>)");

                    //}
                    //catch (Exception ex)
                    //{

                         
                    //}

                 


                    //HtmlNodeCollection invest_list =
                    //  doc.DocumentNode.SelectNodes("//*[@id=\"touzilist\"]");


                    //投资列表HTML标签不标准，导致部分数据被截断

                  //  string touzilist = regexClass.RegexString(HtmlComtent,
             // "(?<g1><section[^>]+id=\"touzilist\">[\\w\\W]+</section>).*?<section[^>]+id=\"syrlist\">", "g1");


                    string pattern = "<(?<HtmlTag>[\\w]+)[^>]*\\sid=(?<Quote>[\"']?)touzilist(?(Quote)\\k<Quote>)[\"']?[^>]*>((?<Nested><\\k<HtmlTag>[^>]*>)|</\\k<HtmlTag>>(?<-Nested>)|.*?)*</\\k<HtmlTag>>";


                    string touzilist = regexClass.AdvanceRegex(HtmlComtent, pattern);




                   HtmlDocument tzDoc = new HtmlDocument();
                    tzDoc.LoadHtml(touzilist);  

                    HtmlNodeCollection invest_list =
                      tzDoc.DocumentNode.SelectNodes("//*[@id=\"touzilist\"]/table/*/tr");



                    string invest_count =
                        doc.DocumentNode.SelectNodes("//*[@id=\"touzilist\"]/div[@class=\"tcaption\"]/span[@class=\"tbadge\"]/text()")[0].InnerText;

                    investList.Add(new JProperty("count", invest_count));

                    JArray invest_array = ParseInvest(invest_list);

                    JArray jdata = new JArray();

                    jdata.Add(invest_array); 

                    investList.Add(new JProperty("invests", jdata));

                    investList.Add(new JProperty("pzie", 10)); 

                    investList.Add(new JProperty("query", CreatePagination("touzi")));

                    investList.Add(new JProperty("comment", "对外投资"));


                    return investList;

                }
                catch (Exception ex)
                {

                    MyLog().Error("对外投资:" + ex.ToString());
                }

                return new JObject();

            }
        
        }




        /// <summary>
        /// 分支机构解析
        /// </summary>
        /// <param name="nodesCollection"></param>
        /// <returns></returns>
        public JArray ParseBrancheList(HtmlNodeCollection nodesCollection) 
        {
            try
            {

                JArray branch_array= new JArray();

                for (int i = 1; i < nodesCollection.Count; i++)
                {
                    HtmlNodeCollection branchListTds = nodesCollection[i].SelectNodes("./td");

                    //企业名称
                    string enterprise_name = GetCellInfo(branchListTds[1].SelectNodes("./div/a/span")[0]);


                    //负责人
                    string resp_name = GetCellInfo(branchListTds[2].SelectNodes("./div/a/h3")[0]);

                    //状态
                    string display_status = GetCellInfo(branchListTds[3].SelectNodes("./span")[0]);

                    JObject branch = new JObject();

                    branch.Add(new JProperty("enterprise_name", enterprise_name));

                    branch.Add(new JProperty("resp_name", resp_name));

                    branch.Add(new JProperty("display_status", display_status));

                    branch_array.Add(branch); 
                }

                return branch_array;

            }
            catch (Exception ex)
            {

                MyLog().Error("分支机构解析:" + ex.ToString());
            }

            return new JArray();

        }


        /// <summary>
        /// 分支机构翻页
        /// </summary>
        /// <param name="htmlContent"></param>
        /// <returns></returns>
        public JArray CallParseBrancheList(string htmlContent)
        {

            try
            {

                HtmlDocument tzDoc = new HtmlDocument();
                tzDoc.LoadHtml(htmlContent);

                HtmlNodeCollection branch_list =
                  tzDoc.DocumentNode.SelectNodes("//table[contains(@class,\"ntable\")]/tr");

                if (branch_list == null)
                {
                    throw new Exception("可能速度太快了!");
                }


                JArray branch_array = ParseBrancheList(branch_list);

                return branch_array;


            }
            catch (Exception ex)
            {

                MyLog().Error("分支机构:" + ex.ToString());
            }

            return new JArray();

        }


        /// <summary>
        /// 分支机构
        /// </summary>
        public JObject BrancheList 
        {
            set {; }
            get {

                try
                {
                    JObject branchList = new JObject();

                    HtmlNodeCollection branch_list =
                    doc.DocumentNode.SelectNodes("//*[@id=\"branchelist\"]/table/tr");

                    string branch_count =
                        doc.DocumentNode.SelectNodes("//*[@id=\"branchelist\"]/div[@class=\"tcaption\"]/span[@class=\"tbadge\"]/text()")[0].InnerText;

                    branchList.Add(new JProperty("count", branch_count));

                    JArray branch_array = ParseBrancheList(branch_list);

                    JArray jdata = new JArray();

                    jdata.Add(branch_array);

                    branchList.Add(new JProperty("branchs", jdata));

                    branchList.Add(new JProperty("pzie", 10)); 

                    branchList.Add(new JProperty("query", CreatePagination("branche")));

                    branchList.Add(new JProperty("comment", "分支机构"));

                    return branchList; 


                }
                catch (Exception ex)
                {

                    MyLog().Error("分支机构:" + ex.ToString());
                }

                return new JObject();
            
             }
        
        }




        /// <summary>
        /// 控股企业解析
        /// </summary>
        /// <param name="nodesCollection"></param>
        /// <returns></returns>
        public JArray ParseHoldco(HtmlNodeCollection nodesCollection) 
        {
            try
            {

                 
                JArray hold_array = new JArray();

                for (int i = 1; i < nodesCollection.Count; i++)
                {
                    HtmlNodeCollection holdTds = nodesCollection[i].SelectNodes("./td");

                    //控股企业名称
                    string enterprise_name = GetCellInfo(holdTds[1].SelectNodes("./div[@class=\"whead-text\"]/a/text()")[0]);


                    //投资比例
                    string share_size = GetCellInfo(holdTds[2].SelectNodes("./text()")[0]);

                    //投资链
                    HtmlNodeCollection chainNodes = holdTds[3].SelectNodes("./div[@class=\"tdpath\"]/*/text()");

                    string path = GetCellInfo(chainNodes[0]);
                    string primary = GetCellInfo(chainNodes[1]);

                    JArray chainArray = new JArray();

                    for (int j = 2; j < chainNodes.Count; j = j+2)
                    {
                        JObject jobj = new JObject();
                        jobj.Add(new JProperty("size", GetCellInfo(chainNodes[j]))); 
                        jobj.Add(new JProperty("secondary", GetCellInfo(chainNodes[j+1])));
                        chainArray.Add(jobj);
                    }

                    JObject shareObject = new JObject(); 
                    shareObject.Add(new JProperty("path", path));
                    shareObject.Add(new JProperty("primary", primary));
                    shareObject.Add(new JProperty("relation", chainArray)); 

                    JObject branch = new JObject();

                    branch.Add(new JProperty("enterprise_name", enterprise_name));

                    branch.Add(new JProperty("share_size", share_size));

                    branch.Add(new JProperty("share_chain", shareObject));

                    hold_array.Add(branch);
                }

                return hold_array; 

            }
            catch (Exception ex)
            {

                MyLog().Error("控股企业解析:" + ex.ToString());
            }

            return  new JArray();
        }



        /// <summary>
        /// 控股企业翻页
        /// </summary>
        /// <param name="htmlContent"></param>
        /// <returns></returns>
        public JArray CallParseHoldco(string htmlContent) 
        {

            try
            {

                HtmlDocument tzDoc = new HtmlDocument();
                tzDoc.LoadHtml(htmlContent);

                HtmlNodeCollection holdco_list =
                  tzDoc.DocumentNode.SelectNodes("//table[contains(@class,\"ntable\")]/tr");

                if (holdco_list == null)
                {
                    throw new Exception("可能速度太快了!");
                }

             
                
                JArray holdco_array = ParseHoldco(holdco_list);

                return holdco_array;


            }
            catch (Exception ex)
            {

                MyLog().Error("控股企业翻页:" + ex.ToString());
            }

            return new JArray();

        }

        /// <summary>
        /// 控股企业
        /// </summary>
        public JObject HoldcoList
        {
            set {; }
            get {

                try
                {

                    JObject holdcoList = new JObject();

                    HtmlNodeCollection holdco_list =
                    doc.DocumentNode.SelectNodes("//*[@id=\"holdcolist\"]/table/tr");

                    string holdco_count =
                        doc.DocumentNode.SelectNodes("//*[@id=\"holdcolist\"]/div[@class=\"tcaption\"]/span[@class=\"tbadge\"]/text()")[0].InnerText;

                    holdcoList.Add(new JProperty("count", holdco_count));

                    JArray holdco_array = ParseHoldco(holdco_list);

                    JArray jdata = new JArray();

                    jdata.Add(holdco_array);

                    holdcoList.Add(new JProperty("holdcos", jdata));

                    holdcoList.Add(new JProperty("pzie", 10)); 

                    holdcoList.Add(new JProperty("query", CreatePagination("holdco")));

                    holdcoList.Add(new JProperty("comment", "控股企业"));

                    return holdcoList; 

                }
                catch (Exception ex)
                {

                    MyLog().Error("控股企业:" + ex.ToString());
                }

                return new JObject();
            
            }
        }

        /// <summary>
        /// 变更记录解析
        /// </summary>
        /// <param name="nodesCollection"></param>
        /// <returns></returns>
        public JArray ParseChangeList(HtmlNodeCollection nodesCollection)
        {
            try
            {


                JArray changes_array = new JArray();

                for (int i = 0; i < nodesCollection.Count; i++)
                {
                    HtmlNodeCollection changesTds = nodesCollection[i].SelectNodes("./td");

                    //变更日期
                    string change_date = GetCellInfo(changesTds[1]);


                    //变更项目
                    string change_item = GetCellInfo(changesTds[2]);

                    //变更前
                    string change_before = GetCellInfo(changesTds[3]);

                    //变更后
                    string change_after = GetCellInfo(changesTds[4]);

                    JObject change = new JObject();

                    change.Add(new JProperty("change_date", change_date));
                    change.Add(new JProperty("change_item", change_item));
                    change.Add(new JProperty("change_before", change_before));
                    change.Add(new JProperty("change_after", change_after)); 
                    changes_array.Add(change);
                }

                return changes_array;

            }
            catch (Exception ex)
            {

                MyLog().Error("变更记录解析:" + ex.ToString());
            }

            return new JArray();
        }
         
        /// <summary>
        /// 变更记录
        /// </summary>
        public JObject ChangeList 
        {
            set {; }
            get
            { 
                try
                {

                    JObject changeList = new JObject();

                    HtmlNodeCollection change_list =
                    doc.DocumentNode.SelectNodes("//*[@id=\"ChangelistTable\"]/table/tr");

                    if (change_list == null)
                    {
                        changeList.Add(new JProperty("message", "没有查到变记录！"));
                        changeList.Add(new JProperty("comment", "变更记录"));
                        return changeList;

                    }

                    string changes_count =
                        doc.DocumentNode.SelectNodes("//*[@id=\"Changelist\"]/div[@class=\"tcaption\"]/span[contains(@class,\"changelistcount\")]/text()")[0].InnerText;

                    changeList.Add(new JProperty("count", changes_count));

                    JArray changes_array = ParseChangeList(change_list);

                    changeList.Add(new JProperty("changes", changes_array));

                    changeList.Add(new JProperty("comment", "变更记录"));

                    return changeList;

                }
                catch (Exception ex)
                { 
                    MyLog().Error("变更记录:" + ex.ToString());
                }

                return new JObject();


            }
        
        }


        public JObject ParseBasicInformation() 
        {
             
            JObject info = new JObject();

            try
            {

                HtmlNodeCollection panelBodys = doc.DocumentNode.SelectNodes("//div[@class=\"panel-body\"]/a");

                Dictionary<string, int> moduleDictionary = new Dictionary<string, int>();

                foreach (HtmlNode panelBody in panelBodys)
                {
                    try
                    {
                        string moduleNameValue = panelBody.InnerText.Replace(" ", "").Replace("\n", "").Trim();

                        if (string.IsNullOrEmpty(moduleNameValue))
                        {
                            continue;
                        }

                        string[] moduleArray = moduleNameValue.Replace("&nbsp;", "$").Split('$');

                        string keyName = moduleArray[0];

                        int keyValue = -1;

                        if (moduleArray.Length == 2)
                        {
                            if (string.IsNullOrEmpty(moduleArray[1]))
                            {
                                continue;
                            }

                            string kv =  regexClass.RegexString(moduleArray[1], "(?<g1>[\\d]+)", "g1");

                            if (string.IsNullOrEmpty(kv))
                            {
                                continue;
                            }

                            try
                            {
                                keyValue = int.Parse(kv);
                            }
                            catch (Exception)
                            {

                                
                            }

                           
                        }

                        if (!moduleDictionary.ContainsKey(keyName))
                        {
                            moduleDictionary.Add(keyName, keyValue);

                        }
                        else

                            moduleDictionary[keyName] = keyValue;

                    }
                    catch (Exception ex)
                    {
                        MyLog().Error("信息打包:" + ex.ToString());

                    }

                }
 



                /*******************基础信息*********************************/

                JObject basic = new JObject();
                basic.Add(new JProperty("company_name", CompanyName));                     //企业名称        
                basic.Add(new JProperty("tag_list", TagList));                             //企业标签 
                basic.Add(new JProperty("phone_num", PhoneNum));                           //电话 
                basic.Add(new JProperty("web_site", WebSite));                             //官网
                basic.Add(new JProperty("mail_box", MailBox));                             //邮箱
                basic.Add(new JProperty("address", Address));                              //公司地址
                basic.Add(new JProperty("intruduce", Intruduce));                          //公司简介 
                basic.Add(new JProperty("comment", "基础信息"));
                info.Add(new JProperty("basic_info", basic));

                /*******************基础信息*********************************/



                /*******************营业执照信息*********************************/

                JObject comInfo = new JObject();
                comInfo.Add(new JProperty("legal_rep", LegalRep));                         //法人代表
                comInfo.Add(new JProperty("registration_status", RegistrationStatus));     //登记状态
                comInfo.Add(new JProperty("build_date", BuildDate));                       //成立
                comInfo.Add(new JProperty("capital", Capital));                            //注册资本
                comInfo.Add(new JProperty("issued_capital", IssuedCapital));               //实缴资本
                comInfo.Add(new JProperty("check_date", CheckDate));                       //核准日期
                comInfo.Add(new JProperty("social_code", SocialCode));                     //统一社会信用代码
                comInfo.Add(new JProperty("organization_code", OrganizationCode));         //组织机构代码
                comInfo.Add(new JProperty("registration_code", RegistrationCode));         //工商注册号
                comInfo.Add(new JProperty("taxpayer_code", TaxpayerCode));                 //纳税人识别号
                comInfo.Add(new JProperty("export_code", ExportCode));                     //进出口企业代码
                comInfo.Add(new JProperty("industry_code", IndustryCode));                 //所属行业
                comInfo.Add(new JProperty("enterprise_type", EnterpriseType));              //企业类型
                comInfo.Add(new JProperty("operation_ending", OperationEnding));            //营业期限
                comInfo.Add(new JProperty("authority", Authority));                         //登记机关
                comInfo.Add(new JProperty("staff_size", StaffSize));                        //人员规模
                comInfo.Add(new JProperty("insured_size", InsuredSize));                    //参保人数
                comInfo.Add(new JProperty("area", Area));                                   //所属地区
                comInfo.Add(new JProperty("once_name", OnceName));                          //曾用名
                comInfo.Add(new JProperty("english_name", EnglishName));                    //英文名
                comInfo.Add(new JProperty("company_address", CompanyAddress));              //企业地址
                comInfo.Add(new JProperty("company_scope", CompanyScope));                  //经营范围

                comInfo.Add(new JProperty("comment", "营业执照信息"));
                info.Add(new JProperty("dcontent", comInfo));

                /*******************营业执照信息*********************************/


                info.Add(new JProperty("partnerslist", PartnernsInfo));       //股东信息
                info.Add(new JProperty("employeeslist", EmployeesList));     //主要人员

                if (moduleDictionary.ContainsKey("对外投资") &&
                    moduleDictionary["对外投资"] > 0 )
                {
                    info.Add(new JProperty("touzilist", InvestList));            //对外投资

                }

                if (moduleDictionary.ContainsKey("分支机构") &&
                   moduleDictionary["分支机构"] > 0)
                {
                    info.Add(new JProperty("branchelist", BrancheList));         //分支机构  

                }

                if (moduleDictionary.ContainsKey("控股企业") &&
                  moduleDictionary["控股企业"] > 0)
                {
                    info.Add(new JProperty("holdcolist", HoldcoList));           //控股企业 

                }

                 
                info.Add(new JProperty("Changelist", ChangeList));               //变更记录

                string muhouactionUrl = "/company_muhouAction?keyNo=" + Unique;
                JObject muhouaction = new JObject();
                muhouaction.Add(new JProperty("url", muhouactionUrl));
                muhouaction.Add(new JProperty("comment", "关系图"));
                info.Add(new JProperty("muhouaction", muhouaction));               //关系图


                if (info.Properties().Count() < 1)
                {
                    info.Add(new JProperty("message", "没有查询到相关的基础信息"));
                }
                else
                {
                    info.Add(new JProperty("unique", this.Unique));
                    info.Add(new JProperty("company_name", this.CompanyName));

                }


                return info;

            }
            catch (Exception ex)
            {
                MyLog().Error("信息打包:" + ex.ToString());

            }

            return new JObject();

        }

        public override string ToString()
        { 
           return  ParseBasicInformation().ToString(); 
        }

    }
}
